package org.yangjie.config.security;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import org.yangjie.service.AuthService;

/**
 * 自定义token认证处理器
 * 模仿: org.springframework.security.authentication.rcp.RemoteAuthenticationProvider
 * @author YangJie [2019年1月21日]
 */
@Component
public class TokenAuthenticationProvider implements AuthenticationProvider{
	
	@Autowired
	private AuthService authService;
	
	
	@Override // 处理自定义token
	public boolean supports(Class<?> authentication) {
		return TokenAuthenticationToken.class.isAssignableFrom(authentication);
	}

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		Object token = authentication.getCredentials();
		if (Objects.isNull(token) || token.toString().trim().isEmpty()) {
        	throw new BadCredentialsException("TOKEN缺失");
        } 
		// 验证token
        String role = authService.get(token.toString());
        if(Objects.isNull(role) || role.trim().isEmpty()) {
        	throw new BadCredentialsException("TOKEN过期");
        }
        // 封装权限
    	List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
		return new TokenAuthenticationToken(authorities);
	}
	
}
